package vip.xiaonuo.issued.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.pojo.httpclient.ReturnJson;
import vip.xiaonuo.core.util.OkHttpUtils;
import vip.xiaonuo.facedoor.iservice.IDeviceSetService;
import vip.xiaonuo.facedoor.modular.device.listener.DeviceChangeTypeEnum;
import vip.xiaonuo.facedoor.modular.device.listener.DevicePublisher;
import vip.xiaonuo.facedoor.modular.device.listener.DeviceSourceEnum;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.mapper.DeviceBaseMapper;
import vip.xiaonuo.facedoor.modular.devicebase.util.DeviceUrlUtil;
import vip.xiaonuo.facedoor.modular.deviceset.constant.DeviceConstant;
import vip.xiaonuo.facedoor.modular.deviceset.entity.DwDeviceSet;
import vip.xiaonuo.facedoor.modular.deviceset.param.DwDeviceSetParam;
import vip.xiaonuo.facedoor.modular.deviceset.service.DwDeviceSetService;
import vip.xiaonuo.facedoor.rule.RuleConstant;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

@Service(RuleConstant.DW+ RuleConstant.DEVICE_SET)
@Slf4j
public class HttpDeviceSetServiceImpl implements IDeviceSetService {


  @Resource
  private DeviceBaseMapper deviceBaseMapper;

  @Resource
  private DwDeviceSetService dwDeviceSetService;

  @Resource
  private DevicePublisher publisher;


  @Override
  public void saveOrUpdate(DwDeviceSetParam dwDeviceSetParam) {
    try {
      DeviceBase deviceBase = deviceBaseMapper.selectById(dwDeviceSetParam.getDeviceBaseId());
      if (ObjectUtil.equal(deviceBase.getDeviceType(),"6")){
        throw new ServiceException(500,"访客机为主动拉取配置信息不支持配置下发!");
      }
      Map<String, Object> map = new HashMap<>();
      String url = MessageFormat.format(DeviceConstant.SET_DEVICE, dwDeviceSetParam.getIp(), dwDeviceSetParam.getCabinetPort());
      map.put("uploadFeaturePath", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/uploadFeature");
      map.put("uploadRecordPath", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/reportData");
      map.put("uploadChildRecordPath", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/uploadChildRecord");
      map.put("uploadPersonVerificationRecordPath", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/uploadIdCardRecord");
//      map.put("reportHealthData", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/reportHealthData");
      map.put("reportHealthData", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/uploadIdCardRecord");
      map.put("getTimePath", "http://" + dwDeviceSetParam.getSeverIp() + ":" + dwDeviceSetParam.getSeverPort() + "/deviceApi/v2.0/getCurrentTime");
      map.put("deviceName", deviceBase.getName());
      map.put("deviceId", deviceBase.getId());
      map.put("key", "ABCD1234");
      if(StringUtils.equals(deviceBase.getDeviceType(),"5")){// 存储柜设备下发特有属性
        map.put("maxUsageNum", dwDeviceSetParam.getMaxUseNum());
        map.put("adminPwd", dwDeviceSetParam.getAdminPwd());
        deviceBase.setMaxUseNum(dwDeviceSetParam.getMaxUseNum());
        deviceBase.setAdminPwd(dwDeviceSetParam.getAdminPwd());
      }
      ReturnJson rj = OkHttpUtils.commonRequest(OkHttpUtils.ReqType.GET, url, map);
      log.info("--------------配置下发--------------");
      if ("0000".equals(rj.getCode())) {
        log.info("配置下发成功");
        log.info("code:" + rj.getCode());
        log.info("data:" + rj.getData());
        log.info("msg:" + rj.getMsg());
        DwDeviceSet deviceSet = dwDeviceSetService.getOne(new LambdaQueryWrapper<DwDeviceSet>().eq(DwDeviceSet::getDeviceBaseId, dwDeviceSetParam.getDeviceBaseId()));
        if (deviceSet == null) {
          dwDeviceSetService.add(dwDeviceSetParam);
        } else {
          dwDeviceSetService.edit(dwDeviceSetParam);
        }
        deviceBase.setCabinetIp(dwDeviceSetParam.getIp());
        deviceBase.setCabinetPort(dwDeviceSetParam.getCabinetPort());
        deviceBaseMapper.updateById(deviceBase);
        publisher.publishEvent(DeviceChangeTypeEnum.EDIT, DeviceSourceEnum.BASE,deviceBase);

      } else if ("0299".equals(rj.getCode())) {
        log.info("配置下发失败");
        log.info("code:" + rj.getCode());
        log.info("data:" + rj.getData());
        log.info("msg:" + rj.getMsg());
        throw new ServiceException(500, "配置下发失败！原因：Key不正确");
      } else {
        throw new ServiceException(500, "无法连接该设备!");
      }
    } catch (Exception e) {
      throw new ServiceException(500, "发生异常！异常信息为：" + ExceptionUtils.getMessage(e));
    }
  }

  @Override
  public void restart(String deviceId) {
    //调用接口远程重启
    String rebootDevice;
    DeviceBase deviceBase = deviceBaseMapper.selectById(deviceId);
    if (StringUtils.isNotBlank(deviceBase.getCabinetIp()) && StringUtils.isNotBlank(deviceBase.getCabinetPort())) {
      Map<String, String> url = DeviceUrlUtil.setUrl(deviceBase);
      rebootDevice = url.get("rebootDevice");
    } else {
      throw new ServiceException(500, "设备：" + deviceBase.getName() + "尚未配置ip及端口");
    }
    if (deviceBase.getDeviceState() != null && !deviceBase.getDeviceState().equals("1")) {
      throw new ServiceException(500, "远程重启失败！设备未在线");
    } else {
      Map<String, Object> map = new HashMap<>();
      map.put("key", "ABCD1234");
      ReturnJson rj = OkHttpUtils.commonRequest(OkHttpUtils.ReqType.GET, rebootDevice, map);
      if (!(StringUtils.isNotBlank(rj.getCode()) && "0000".equals(rj.getCode()))) {
        throw new ServiceException(500, "设备远程重启失败，原因：{code:" + rj.getCode() + "}" + rj.getMsg());
      }
    }
  }
}
